package com.ctshk.common.utils;

import cn.hutool.core.util.IdUtil;

import com.ctshk.common.exception.CtsException;
import com.itextpdf.text.DocumentException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 中汽巴士接口工具类
 */
public class RglBusUtil {
	protected static Logger logger = LoggerFactory.getLogger(RlgOrderUtil.class);

    private static final String url = "http://test.hkcts.hebuyun.com:9090/tsp/";
    private static final String sellWay = "0000";
    private static final String appKey = "F7466F863A986EC53FED570124478997";
    private static final String appSecret = "225CC17E1C30CD62";
    private static final String operID = "publicTst";
    private static final String loginName = "publicTst";
    private static final String password = "000000";
    private static final String branchID = "999009";
    private static final String flag = "Y";


    /**
     * 登录接口 REQ2001
     * @param interfaceId 接口编码
     * @return
     */
    public static Map<String,Object> login(String interfaceId) throws DocumentException {

        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2001>"+
                "<LoginName>"+loginName+"</LoginName>"+
                "<Password>"+password+"</Password>"+
                "</REQ2001>"+
                "</BODY>"+
                "</ROOT>";
//        System.out.println("登录接口请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }

    /**
     * 获取城市列表 REQ2003
     * @param interfaceId 接口编码
     * @return
     */
    public static Map<String,Object> getCityList(String interfaceId) throws DocumentException {

        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2003>"+
                "</REQ2003>"+
                "</BODY>"+
                "</ROOT>";
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 获取站点列表 REQ2003
     * @param interfaceId 接口编码
     * @return
     */
    public static Map<String,Object> getSiteList(String interfaceId) throws DocumentException {

        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2003>"+
                "<DynamicSite>"+flag+"</DynamicSite>"+
                "</REQ2003>"+
                "</BODY>"+
                "</ROOT>";
//        System.out.println("获取站点列表请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 车次批量查询 REQ2044
     * @param paramMap 接口入参
     * @return
     */
    public static Map<String,Object> getAllSiteList(Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2044>>"+
                "<DepartureCityNo>"+paramMap.get("departureCityNo")+"</DepartureCityNo>"+
                "<ArrivalCityNo>"+paramMap.get("arrivalCityNo")+"</ArrivalCityNo>"+
                "<DepartureDate>"+paramMap.get("departureDate")+"</DepartureDate>"+
                "</REQ2044>>"+
                "</BODY>"+
                "</ROOT>";
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 车次信息查询 REQ2004
     * @param paramMap 接口入参
     *       interfaceId      接口编码
     *       departureCityNo 出发城市编号
     *       arrivalCityNo  到达城市编码
     *       departureDate 出发日期 (格式 YYYYMMDD)
     *       timePart 时间区间（0000-0600 表示 00:00 分至 06:00 分之间的班次，有如下几个区间 {0000-0600,0600- 1200,1200- 1800,1800-2400}）
     *                 此项用于班次筛选，不传即查全天班次
     *       onStationCode 登车点编码
     *       offStationCod 落车点代码
     * @return
     */
    public static Map<String,Object> getshiftList(Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2004>"+
                "<DepartureCityNo>"+paramMap.get("departureCityNo")+"</DepartureCityNo>"+
                "<ArrivalCityNo>"+paramMap.get("arrivalCityNo")+"</ArrivalCityNo>"+
                "<DepartureDate>"+paramMap.get("departureDate")+"</DepartureDate>";
        if(StringUtils.isNotBlank((String)paramMap.get("timePart"))){
            xmlInfo =  xmlInfo + "<TimePart>"+paramMap.get("timePart")+"</TimePart>";
        }
        xmlInfo = xmlInfo +
                "<OnStationCode>"+paramMap.get("onStationCode")+"</OnStationCode>"+
                "<OffStationCode>"+paramMap.get("offStationCode")+"</OffStationCode>"+
                "</REQ2004>"+
                "</BODY>"+
                "</ROOT>";
        System.out.println("查询班次请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }

    /**
     * 下单锁座接口 REQ2005
     * @param paramMap 接口入参
     *       interfaceId      接口编码
     *       busNo 车次编号
     *       ticketNumStr  各票种数量字符串
     *       departureCityNo 出发城市编码
     *       arrivalCityNo 到达城市编码
     *       onStationNo 登车点编号
     *       offStationNo 落车点编号
     *       departureDate date
     *       currency  支付币种
     *       userNickName 用户预留昵称
     *       userTelNo 用户预留手机号
     * @return
     */
    public static Map<String,Object> placeOrderLockSeat(Map<String,Object> paramMap) {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2005>"+
                "<BusNo>"+paramMap.get("busNo")+"</BusNo>"+
                "<TicketNumStr>"+paramMap.get("ticketNumStr")+"</TicketNumStr>"+
                "<DepartureCityNo>"+paramMap.get("departureCityNo")+"</DepartureCityNo>"+
                "<ArrivalCityNo>"+paramMap.get("arrivalCityNo")+"</ArrivalCityNo>"+
                "<OnStationNo>"+paramMap.get("onStationNo")+"</OnStationNo>"+
                "<OffStationNo>"+paramMap.get("offStationNo")+"</OffStationNo>"+
                "<DepartureDate>"+paramMap.get("departureDate")+"</DepartureDate>"+
                "<Currency>"+paramMap.get("currency")+"</Currency>"+
                "<DepartureDate>"+paramMap.get("departureDate")+"</DepartureDate>";
                if(StringUtils.isNotBlank((String)paramMap.get("preferentialAmount"))){
                    xmlInfo =  xmlInfo + "<PreferentialAmount>"+paramMap.get("preferentialAmount")+"</PreferentialAmount>";
                }else{
                    xmlInfo = xmlInfo +"<PreferentialAmount/>";
                }

        xmlInfo = xmlInfo +
                "<UserNickName>"+paramMap.get("userNickName")+"</UserNickName>"+
                "<UserTelNo>"+paramMap.get("userTelNo")+"</UserTelNo>"+
                "</REQ2005>"+
                "</BODY>"+
                "</ROOT>";
        
        Long curTime = System.currentTimeMillis();
        logger.info("[sid : {}] 巴士中汽下单锁座开始 [url : url] [data : {}]", curTime, url, xmlInfo);
        try {
        	String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        	logger.info("[sid : {}] 巴士中汽下单锁座结束 [result : {}] [callTime : {}]", curTime, resultInfo, System.currentTimeMillis() - curTime);
        	return ParseXmlUtil.parseXml(resultInfo);
		} catch (Exception e) {
			logger.error("[sid : {}] 巴士中汽下单锁座异常 [callTime : {}]", curTime, System.currentTimeMillis() - curTime, e);
			throw new CtsException("巴士中汽下单锁座异常", e);
		}
    }


    /**
     * 出票接口 REQ2006
     * @param paramMap 接口入参
     *         interfaceId      接口编码
     *         payType 支付方式（1：现金 (备用金用户选此 项 ) ， 2 ： 刷 卡 ， 3：OPEN 票劵，4： 用户储值 ，5：微 信支付，6：支付 宝）详见附录支付 方式字典
               sellWay 销售渠道代码，同请求头
               currencyType 币种（1,人民币 2, 港币）
               extPayRefNo 外部支付参考号
               extPayDateTime 线上支付的支付时 间 (格式 YYYYMMDDHHMMSS)
               extPayOrderNo 线上支付的支付订 单号
               extOrderNo 第三方系统订单号
     * @return
     */
    public static Map<String,Object> drawerOrder (Map<String,Object> paramMap) {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2006>"+
                "<OrderNo>"+paramMap.get("orderNo")+"</OrderNo>"+
                "<PayType>"+paramMap.get("payType")+"</PayType>"+
                "<VoucherNo/>"+
                "<SellWay>"+paramMap.get("sellWay")+"</SellWay>"+
                "<CurrencyType>"+paramMap.get("currencyType")+"</CurrencyType>"+
                "<ExtPayRefNo>"+paramMap.get("extPayRefNo")+"</ExtPayRefNo>"+
                "<ExtPayDateTime>"+paramMap.get("extPayDateTime")+"</ExtPayDateTime>"+
                "<ExtPayOrderNo>"+paramMap.get("extPayOrderNo")+"</ExtPayOrderNo>"+
                "</REQ2006>"+
                "</BODY>"+
                "</ROOT>";
        
        Long curTime = System.currentTimeMillis();
        logger.info("[sid : {}] 巴士中汽下单出票开始 [url : url] [data : {}]", curTime, url, xmlInfo);
        try {
        	String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        	logger.info("[sid : {}] 巴士中汽下单出票结束 [result : {}] [callTime : {}]", curTime, resultInfo, System.currentTimeMillis() - curTime);
        	return ParseXmlUtil.parseXml(resultInfo);
		} catch (Exception e) {
			logger.error("[sid : {}] 巴士中汽下单出票异常 [callTime : {}]", curTime, System.currentTimeMillis() - curTime, e);
			throw new CtsException("巴士中汽下单出票异常", e);
		}
    }

    /**
     * 已售车票查询接口 REQ2007
     * @param paramMap 接口入参
     *        orderNo 订单号
     *        isGetOrder 是否查询整个订单 1，通过票号查整个订单下的票信息；0，查询单张票
     * @return
     */
    public static Map<String,Object> querySaledOrder (Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        String ticketNo = paramMap.get("ticketNo") != null ? (String)paramMap.get("ticketNo") : "";
        String orderNo = paramMap.get("orderNo") != null ? (String)paramMap.get("orderNo") : "";
        String isGetOrder = paramMap.get("isGetOrder") != null ? (String)paramMap.get("isGetOrder") : "";
        String userTelNo = paramMap.get("userTelNo") != null ? (String)paramMap.get("userTelNo") : "";
        String extOrderNo = paramMap.get("extOrderNo") != null ? (String)paramMap.get("extOrderNo") : "";
        String forPrintFlag = paramMap.get("forPrintFlag") != null ? (String)paramMap.get("forPrintFlag") : "";

        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2007>"+
                "<TicketNo>"+ticketNo+"</TicketNo>"+
                "<OrderNo>"+orderNo+"</OrderNo>"+
                "<IsGetOrder>"+isGetOrder+"</IsGetOrder>"+
                "<UserTelNo>"+userTelNo+"</UserTelNo>"+
                "<ExtOrderNo>"+extOrderNo+"</ExtOrderNo>"+
                "<ForPrintFlag>"+forPrintFlag+"</ForPrintFlag>"+
                "</REQ2007>"+
                "</BODY>"+
                "</ROOT>";
        System.out.println("已售车票查询接口请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }

    /**
     * 退票接口 REQ2008
     * @param paramMap 接口入参
     *        ticketNo 车票号
     *        confirmFlag 1，只查询退票金额 不退票，其他值执行退票
     *        forceReturnFlag 1：表强制退票不收 取手续费，0：按正 常流程退票
     * @return
     */
    public static Map<String,Object> refundOrder (Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2008>"+
                "<TicketNo>"+paramMap.get("ticketNo")+"</TicketNo>"+
                "<ConfirmFlag>"+paramMap.get("confirmFlag")+"</ConfirmFlag>"+
                "<ForceReturnFlag>"+paramMap.get("forceReturnFlag")+"</ForceReturnFlag>"+
                "</REQ2008>"+
                "</BODY>"+
                "</ROOT>";
        System.out.println("退票接口请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 改签接口 REQ2009
     * @param paramMap 接口入参
     *        originalTicketNo 原票号
     *        newBusNo 新选班次号
     *        newDepartureDate 新选出发日期(格式 YYYYMMDD)
     * @return
     */
    public static Map<String,Object> endorseOrder (Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2009>"+
                "<OriginalTicketNo>"+paramMap.get("originalTicketNo")+"</OriginalTicketNo>"+
                "<NewBusNo>"+paramMap.get("newBusNo")+"</NewBusNo>"+
                "<NewDepartureDate>"+paramMap.get("newDepartureDate")+"</NewDepartureDate>"+
                "</REQ2009>"+
                "</BODY>"+
                "</ROOT>";
        System.out.println("改签接口请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 订单取消接口 REQ2011
     * @param paramMap 接口入参
     *        orderNo 订单号
     * @return
     */
    public static Map<String,Object> cancelOrder (Map<String,Object> paramMap) throws DocumentException {
        String interfaceId = (String)paramMap.get("interfaceId");
        String xmlInfo = getXmlHeadInfo(interfaceId,IdUtil.randomUUID());
        xmlInfo = xmlInfo +"<BODY>"+
                "<REQ2011>"+
                "<OrderNo>"+paramMap.get("orderNo")+"</OrderNo>"+
                "</REQ2011>"+
                "</BODY>"+
                "</ROOT>";
        System.out.println("取消订单接口请求报文:"+xmlInfo);
        String resultInfo = HttpUtils.xmlSendByPost(url,xmlInfo);
        return ParseXmlUtil.parseXml(resultInfo);
    }


    /**
     * 组装报文请求头
     * @param interfaceId
     * @param msgId
     * @return
     */
    private static String getXmlHeadInfo(String interfaceId,String msgId) {
        String headXml = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<ROOT>" +
                "<HEAD>" +
                "<App>COUNTER-CLIENT</App>" +
                "<Ver>1000</Ver>" +
                "<MsgID>" + msgId + "</MsgID>" +
                "<MsgCode>" + interfaceId + "</MsgCode>" +
                "<SellWay>" + sellWay + "</SellWay>" +
                "<AppKey>" + appKey + "</AppKey>" +
                "<AppSecret>" + appSecret + "</AppSecret>" +
                "<OperID>" + operID + "</OperID>" +
                "<BranchID>" + branchID + "</BranchID>" +
                "</HEAD>";
        return headXml;
    }




}
